import axios from "@/util/request.js"
const utils = {
	// 时间格式化
	formatTimeRange(timeRange) {
		if(timeRange) {
			// 使用正则表达式提取开始日期和结束日期部分
			 const dateRegex = /(\d{1,2}\/\d{1,2}\/\d{4})/g;
			 const dates = timeRange.match(dateRegex);
					
			 if (!dates || dates.length < 2) {
			   // 如果无法提取日期部分或日期部分不足两个，则返回原始字符串
			   return timeRange;
			 }
					
			 const startDate = new Date(dates[0]);
			 // const endDate = new Date(dates[1]);
			  const parts = dates[1].split('/');
			   if (parts.length === 3) {
			     const day = parts[0];
			     const month = parts[1];
			     const year = parts[2];
			      var endDates =  `${year}-${month}-${day}`;
			   } 
			 // 格式化日期部分
			 const startYear = startDate.getFullYear();
			 const startMonth = (startDate.getMonth() + 1).toString().padStart(2, '0');
			 const startDay = startDate.getDate().toString().padStart(2, '0');
			 // const endYear = endDate.getFullYear();
			 // const endMonth = (endDate.getMonth() + 1).toString().padStart(2, '0');
			 // const endDay = endDate.getDate().toString().padStart(2, '0');
					
			 // 组合为格式化后的字符串
			 const formattedTimeRange = `${startYear}-${startMonth}-${startDay} 至 ${endDates}`;
					
			 return formattedTimeRange;
		}
	},
	/**
	 * 截取第一张图片方法
	 * @param {Object} info
	 */
	imagePath(info) {
		if (info) {
			return axios.interfaceUrl() + info.split(",")[0];
		} else {
			return ''
		}
	},
	// 首页柱状图排序
	getreserve(key) {
		for (let h = 0 ; h < key.length;key++) {
			console.log(h,'h')
		}
		debugger
		var yars =  []
		let keyArr = new Array()
		let valArr = new Array()
		let sortArr = new Array()
		if (key == '01') {
			yars[0] = key
		}
		if (key == '02') {
			yars[1] = key
		}
		if (key == '03') {
			yars[2] = key
		}
		if (key == '04') {
			yars[3] = key
		}
		if (key == '05') {
			yars[4] = key
		}
		if (key == '06') {
			yars[5] = key
		}
		if (key == '07') {
			yars[6] = key
		}
		if (key == '08') {
			yars[7] = key
		}
		if (key == '09') {
			yars[8] = key
		}
		if (key == '10') {
			yars[9] = key
		}
		if (key == '11') {
			yars[10] = key
		}
		if (key == '12') {
			yars[11] = key
		}
		return yars
	},
	trimHtml(value) {

		value = value.replace(/&nbsp;/ig, "")
		value = value.replace(/(\n)/g, "");
		value = value.replace(/(\t)/g, "");
		value = value.replace(/(\r)/g, "");
		value = value.replace(/<\/?[^>]*>/g, "");
		value = value.replace(/\s*/g, "");

		return value
	},
	getCounterPath() {
		var path = axios.interfaceUrl().replace("renren-api", "counter/")
		return utils.encryption(path)
	},
	getIsGuoNeng() {
		var flag = 0
		if (axios.interfaceUrl().indexOf("v2.zygyx.com") != -1) {
			flag = 1
		}
		return flag

	},
	formatUploadImageStr(images) {
		var arr = new Array()
		if (images) {

			var imagesArr = images.split(",")
			imagesArr.forEach((item) => {
				arr.push(axios.interfaceUrl() + item)
			})

		}
		return arr

	},
	formatUploadImageArr(arr) {
		var a = new Array()
		arr.forEach((item) => {
			a.push(axios.interfaceUrl() + item)
		})
		return a
	},
	formatTime() {
		var now = new Date();

		var year = now.getFullYear(); //年
		var month = now.getMonth() + 1; //月
		var day = now.getDate(); //日
		var clock = year + "-";
		if (month < 10)
			clock += "0";
		clock += month + "-";
		if (day < 10)
			clock += "0";
		clock += day;

		return (clock);
	},
	getInitApp(str) {
		return `${uni.getStorageSync("initAppData")}.${str}`
	},
	/**
	 * 查找数组下标
	 * @param {Object} data
	 * @param {Object} id
	 */
	findArrIndex(data, id) {
		return data.findIndex(item => {
			if (item.id == id) {
				return true;
			}
		})
	},
	/**
	 * 获取UUID
	 */
	getUUID() {
		var d = new Date().getTime();
		if (window.performance && typeof window.performance.now === "function") {
			d += performance.now(); //use high-precision timer if available
		}
		var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
		});
		return uuid;
	},

	getFileSuffix(fileName) {
		return fileName.split('.').pop().toLowerCase()
	},
	subStr(str, start, n) {
		if (!str) {
			return ""
		}
		if (str.replace(/[\u4e00-\u9fa5]/g, '**').length <= n) {
			return str;
		}
		let len = 0;
		let tmpStr = '';
		for (let i = start; i < str.length; i++) { // 遍历字符串
			if (/[\u4e00-\u9fa5]/.test(str[i])) { // 中文 长度为两字节
				len += 2;
			} else {
				len += 1;
			}
			if (len > n) {
				break;
			} else {
				tmpStr += str[i];
			}
		}
		return tmpStr;
	},
	/**
	 * JSON对象转字符串
	 * @param {Object} res
	 */
	encryption(res) {
		return encodeURIComponent(JSON.stringify(res))
	},
	/**
	 * 字符串转JSON对象
	 * @param {Object} res
	 */
	decrypt(res) {
		return JSON.parse(decodeURIComponent(res))
	},
	formatTime(dateTimeStamp) {
		var minute = 1000 * 60;
		var hour = minute * 60;
		var day = hour * 24;
		var halfamonth = day * 15;
		var month = day * 30;
		var year = day * 365;
		var now = new Date().getTime();
		var diffValue = now - dateTimeStamp * 1000;
		if (diffValue < 0) {
			return;
		}
		var yearC = diffValue / year;
		var monthC = diffValue / month;
		var weekC = diffValue / (7 * day);
		var dayC = diffValue / day;
		var hourC = diffValue / hour;
		var minC = diffValue / minute;

		var timeMsg = "刚刚";
		if (yearC >= 1) {
			timeMsg = "" + parseInt(yearC) + "年前";
		}
		if (monthC >= 1) {
			timeMsg = "" + parseInt(monthC) + "月前";
		} else if (weekC >= 1) {
			timeMsg = "" + parseInt(weekC) + "周前";
		} else if (dayC >= 1) {
			timeMsg = "" + parseInt(dayC) + "天前";
		} else if (hourC >= 1) {
			timeMsg = "" + parseInt(hourC) + "小时前";
		} else if (minC >= 1) {
			timeMsg = "" + parseInt(minC) + "分钟前";
		}

		return timeMsg;
	},
	isMobile (mobile) {  
	  var test = /^1[3-9]\d{9}$/.test(mobile)
	  if(!test){
		  return false
	  }
	  return true
	},
	downLoad(url) {
		wx.downloadFile({
			url: url,
			success: (res) => {
				if (res.statusCode === 200) {
					var temp = res.tempFilePath
					wx.saveFile({
						tempFilePath: temp,
						success: (res) => {

							let saveFilePath = res.savedFilePath
							let suffix = utils.getFileSuffix(saveFilePath)
							wx.openDocument({
								filePath: saveFilePath,
								fileType: suffix,
								showMenu: true,
								success: (res) => {}
							})
						}
					})
				} else {
					wx.showModal({
						title: '提示:',
						content: '当前文件发生异常,请联系管理员',
						showCancel: false,
						cancelText: '取消',
						cancelColor: '#000000',
						confirmText: '确定',
						confirmColor: '#3CC51F'
					})
				}
			},
			fail: () => {
				wx.showModal({
					title: '提示:',
					content: '当前文件发生异常,请联系管理员',
					showCancel: false,
					cancelText: '取消',
					cancelColor: '#000000',
					confirmText: '确定',
					confirmColor: '#3CC51F'
				})
			}
		})
	},
	counter(areaIndex = 0, companyIndex = 0, typeIndex = 0, benchmarkPrice = 0, quantity = 0, company_divide = 0,
		server_price = 0, avg_price = 0) {
		let price = 0
		let total = 0
		//areaIndex：地区
		//companyIndex：公司
		//typeIndex：模式
		//年用电量：quantity
		//公司占比：company_divide
		//服务费单价：server_price
		//长协均价：  avg_price   
		//上限基准价：benchmarkPrice 

		var quantity = parseFloat(quantity) * 10000
		var company_divide = parseFloat(company_divide)
		var server_price = parseFloat(server_price)
		var avg_price = parseFloat(avg_price)
		var benchmarkPrice = parseFloat(benchmarkPrice)

		//江苏
		if (areaIndex == 1002) {
			if (companyIndex == 0) {
				//国能
				if (typeIndex == 'BILI') {
					//分成
					total = quantity * 0.9 * (benchmarkPrice - avg_price) * company_divide / 100 * 0.9
				} else {
					//服务费
					total = quantity * 0.9 * server_price * 0.9
				}

			}

			if (companyIndex == 1) {
				//国网
				if (typeIndex == 'BILI') {
					total = quantity * 0.9 * (benchmarkPrice - avg_price) * company_divide / 100 * 0.8
				} else {
					total = quantity * 0.9 * server_price * 0.8
				}

			}

		}

		//山东
		if (areaIndex == 1003) {
			total = quantity * 0.85 * server_price * 0.8
		}

		if (areaIndex == 1004) {
			total = 0
		}
		price = total * (100 - 19) / 100
		if (isNaN(price)) {
			price = 0
		}
		return parseInt(price)
	}
}


export default utils
